# create a file of excel about data
from prj001.serializers import InfoSerializer, OtherTablesSerializer

from prj001.constants import get_chinese

from django.conf import settings

import pandas as pd
import time

from .excelconstants import true_change_bool, summary_menstruation
from .excelconstants import history_table, excel_title_style

SAVE_EXCEL_PATH = settings.NGINX_EXCEL_PATH
SAVE_SERVER_PORT = ':'.join((settings.NGINX_SERVER, settings.NGINX_PORT))


def str_to_bool(data):
    for key, value in true_change_bool.items():
        if data.get(key) in ['true', 'True']:
            pass


def save_excel(data, user_id):
    file_name = ''.join((str(round(time.time())),
                         '-',
                         str(user_id),
                         '.xlsx'))
    file_path = ''.join((SAVE_EXCEL_PATH, file_name))

    writer = pd.ExcelWriter(file_path,
                            engine='xlsxwriter')
    df = pd.DataFrame()
    df.to_excel(writer, sheet_name='患者信息', index=False)
    wb = writer.book
    ws = writer.sheets['患者信息']

    new_dict = {}
    title_index = 0

    ws.set_row(0, 25)

    for p, q in get_chinese.items():
        style_header = wb.add_format(excel_title_style[p])
        for index, key in enumerate(q.keys()):
            new_dict.update({key: title_index})
            ws.write(0, title_index, q.get(key), style_header)
            title_index += 1

    p = 1
    for index, value in enumerate(data):
        # name = value.get('info').get('name')
        # ws.write(p, q, name)
        ws.set_row(p, 22)
        for k, v in value.items():
            # {table}
            if v:
                for inner_k, inner_v in v.items():

                    if k == 'summary' and (inner_k in summary_menstruation.keys()):
                        col_index = new_dict.get('s_%s' % inner_k)
                    elif k == 'history' and (inner_k in history_table.keys()):
                        col_index = new_dict.get('h_%s' % inner_k)
                    else:
                        col_index = new_dict.get(inner_k)

                    if not isinstance(col_index, int):
                        continue
                    # user every single data
                    ws.write(p, col_index, inner_v)
                    # if inner_k == 'belly_juan' or inner_k == 'body_waist':
                    #     print(inner_k, inner_v, type(inner_v), '=====')
                    if isinstance(inner_v, bool):
                        if inner_v:
                            ws.write(p, col_index, '是')
                        else:
                            ws.write(p, col_index, '否')
                    elif isinstance(inner_v, str) and inner_v in ['true', 'True']:
                        ws.write(p, col_index, '是')

        p += 1
    try:
        writer.save()
    except Exception as e:
        raise ValueError('%s' % e)

    return ''.join((SAVE_SERVER_PORT, settings.NGINX_PATH, file_name))


def save_excel_results(sf, request, id_list=None, md=None, resp_data_list=None):
    for id_ in id_list:
        data = {
            'info': None,
        }
        try:
            instance = md.objects.get(id=id_)
        except md.DoesNotExist:
            if not instance:
                data['info'] = None
            instance = None
        if instance:
            s = InfoSerializer(instance=instance,
                               context={'request': request})

            data['info'] = s.data

            other_s = OtherTablesSerializer(instance=instance,
                                            context={'request': request})
            data.update(other_s.data)
            resp_data_list.append(data)
    try:
        file_path = save_excel(resp_data_list, request.user.id)
    except Exception as e:
        raise ValueError('%s' % e)

    return file_path
